﻿using BlossomiShymae.GrrrLCU;
using Common.Untils;
using HandyControl.Controls;
using LOLApi;
using LOLApi.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;

namespace Tryit.ViewModels
{
    public class SettingsViewModel : BindableBase, INavigationAware
    {
        private static AllSettings _cachedSettings;
        private static bool _isSettingsLoaded;
        public AllSettings Settings = new AllSettings();
        private string programName = "client.exe"; // 英雄联盟客户端程序名
        private string findedPath = string.Empty;
        private bool find = false;//默认未找到
        /// <summary>
        /// 用户
        /// </summary>
        private string _user;
        public string User
        {
            get { return _user; }
            set { SetProperty(ref _user, value); }
        }
        /// <summary>
        /// 密码
        /// </summary>
        private string _password;
        public string Password
        {
            get { return _password; }
            set { SetProperty(ref _password, value); }
        }
        /// <summary>
        /// 客户端地址
        /// </summary>
        private string _clientAddress;
        public string ClientAddress
        {
            get { return _clientAddress; }
            set { SetProperty(ref _clientAddress, value); }
        }
        /// <summary>
        /// 自动接受对局
        /// </summary>
        private bool _autoAcceptGame;
        public bool AutoAcceptGame
        {
            get { return _autoAcceptGame; }
            set { SetProperty(ref _autoAcceptGame, value); }
        }
        /// <summary>
        /// 自动下一句
        /// </summary>
        private bool _autoNextGame;
        public bool AutoNextGame
        {
            get { return _autoNextGame; }
            set { SetProperty(ref _autoNextGame, value); }
        }

        public DelegateCommand SaveSettings => new DelegateCommand(SaveToFile);
        public ObservableCollection<string> QfList => new ObservableCollection<string> { "艾欧尼亚", "祖安", "诺克萨斯", "班德尔城", "皮尔特沃夫", "战争学院", "巨神峰", "雷瑟守备", "裁决之地", "黑色玫瑰", "暗影岛", "钢铁烈阳", "水晶之痕", "均衡教派", "影流", "守望之海", "征服之海", "卡拉曼达", "皮城警备", "比尔吉沃特", "德玛西亚", "弗雷尔卓德", "无畏先锋", "恕瑞玛", "扭曲丛林", "巨龙之巢", "男爵领域", "峡谷之巅", "教育网专区" };

        public SettingsViewModel()
        {
            // 构造函数中不执行初始化，等待导航时执行
        }

        private async Task InitClientPathAsync()
        {
            if (find) return;

            await Task.Run(() =>
            {
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo drive in drives)
                {
                    if (find) break;
                    if (drive.IsReady && drive.DriveType == DriveType.Fixed)
                    {
                        try
                        {
                            var files = Directory.GetFiles(drive.RootDirectory.FullName, programName, SearchOption.AllDirectories);
                            if (files.Length > 0)
                            {
                                findedPath = files[0];
                                find = true;
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            // 忽略访问权限错误
                            continue;
                        }
                    }
                }
            });

            if (find)
            {
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    ClientAddress = findedPath;
                    Settings.ClientAddress = findedPath;
                });
            }
            else
            {
                Growl.Warning("未找到客户端文件,请尝试手动添加");
            }
        }

        private async Task InitDataAsync()
        {
            if (_isSettingsLoaded)
            {
                // 使用缓存的设置
                Settings = _cachedSettings ?? new AllSettings();
                LoadSettingsToProperties();
                return;
            }

            string file = Path.Combine(Environment.CurrentDirectory, "settings.json");
            if (!File.Exists(file))
            {
                _cachedSettings = new AllSettings();
                Settings = _cachedSettings;
                _isSettingsLoaded = true;
                return;
            }

            try
            {
                string jsonString = await File.ReadAllTextAsync(file);
                Settings = JsonSerializer.Deserialize<AllSettings>(jsonString) ?? new AllSettings();
                _cachedSettings = Settings;
                _isSettingsLoaded = true;

                LoadSettingsToProperties();

                if (string.IsNullOrEmpty(ClientAddress))
                {
                    await InitClientPathAsync();
                }
            }
            catch (Exception ex)
            {
                Growl.Error($"加载配置文件失败: {ex.Message}");
                Settings = new AllSettings();
                _cachedSettings = Settings;
                _isSettingsLoaded = true;
            }
        }

        private void LoadSettingsToProperties()
        {
            if (Settings == null)
            {
                Settings = new AllSettings();
            }

            AutoAcceptGame = Settings.AutoAcceptGame;
            AutoNextGame = Settings.AutoNextGame;
            User = Settings.User ?? string.Empty;
            Password = Settings.Password ?? string.Empty;
            ClientAddress = Settings.ClientAddress ?? string.Empty;
        }

        private async void SaveToFile()
        {
            try
            {
                // 确保Settings对象被初始化
                if (Settings == null)
                {
                    Settings = new AllSettings();
                }

                // 确保所有属性都被正确赋值
                Settings.AutoAcceptGame = AutoAcceptGame;
                Settings.AutoNextGame = AutoNextGame;
                Settings.User = User ?? string.Empty;
                Settings.Password = Password ?? string.Empty;
                Settings.ClientAddress = ClientAddress ?? string.Empty;

                string file = Path.Combine(Environment.CurrentDirectory, "settings.json");
                string jsonString = JsonSerializer.Serialize(Settings, new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
                });
                
                await File.WriteAllTextAsync(file, jsonString);
                
                _cachedSettings = Settings;
                await RefreshSettingsAsync();
                
                Growl.Success("配置保存成功!");
            }
            catch (Exception ex)
            {
                Growl.Error($"保存配置失败: {ex.Message}");
            }
        }

        private async Task RefreshSettingsAsync()
        {
            string file = Path.Combine(Environment.CurrentDirectory, "settings.json");
            if (!File.Exists(file)) return;

            try
            {
                string jsonString = await File.ReadAllTextAsync(file);
                Account.AllSettings = JsonSerializer.Deserialize<AllSettings>(jsonString);
            }
            catch (Exception ex)
            {
                Growl.Error($"刷新配置失败: {ex.Message}");
            }
        }

        async void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
        {
            await InitDataAsync();
        }

        bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
        {
            return;
        }
    }
}
